import { Component } from '@angular/core';

import { Platform, MenuController, NavController, LoadingController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { filter } from 'rxjs/operators';
import { MobileAccessibility } from '@ionic-native/mobile-accessibility/ngx';
import { TabsService } from './core/tabs.service';
import { HttpService } from './service/http.service';
import { ToolService } from './service/tool.service';
import { UrlService } from './service/url.service';
import { ConfigService } from './service/config.service';
import { Router, NavigationEnd } from '@angular/router';
import { EventService } from './service/event.service';
import { ThemeService } from './service/theme.service';
import { Storage } from '@ionic/storage';
import * as $ from 'jquery';
import { Network } from '@ionic-native/network/ngx';
import { PopwinService } from './service/popwin.service';
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { FileTransfer,FileUploadOptions,FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  public lots = [];
  public selectedTheme: any;
  public nickName: string; //用户的昵称
  public money: any = "0";//可用余额
  public avatarImg: string;//用户的头像
  public isAvatar: boolean;//是否有头像
  private alertNoticeData: any[] = [];//公告的所有数据临时存储
  private selectNoticeMark: number = -1;//选中的第几条公告
  public noticeData = { "title": '', "content": "" };


  //第三方游戏相关
  public thirdInputVal = "";
  public isShowThirdWin = false;  //是否呼出第三方游戏弹出的页面
  public allBalance = "0.00";//平台的总可用余额
  public thirdBalance = "0.00"; //第三方的金额
  public thirdPlatformID = "";//第三方的平台id
  public thirdName = ""; //第三方的名字
  public playType = "";//1是真人，2是游戏

  //app的更新操作
  public isForce = false;  //是否强制更新
  public iosDownUrl = "";  //ios的下载链接
  public androidDownUrl = "";  //android的下载链接
  public updateContent = "";  //更新的内容
  public isUpdate = false; //是否更新(默认false不更新)
  public versionNo="";  //版本号


  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public tabs: TabsService, private http: HttpService, private router: Router, private menu: MenuController, private eventS: EventService, private navCtrl: NavController, private theme: ThemeService
    , private store: Storage, private network: Network, private popWin: PopwinService, private mobileAccessibility: MobileAccessibility,private loading:LoadingController,private file:File,private fileOpener:FileOpener,private transfer:FileTransfer,private iab:InAppBrowser) {
    this.initializeApp();
    this.getSetData();//获取数据是否加密处理 
    this.menuNet();//获取侧滑菜单
    this.initEvent();//初始化事件
    this.alertNotice();//弹出公告

  }

  initializeApp() {
    let that = this;
    this.theme.getActiveTheme().subscribe(val => that.selectedTheme = val);
    this.platform.ready().then(() => {
      this.splashScreen.hide();
      this.statusBar.show();
      if (this.platform.is('android')) {
        if (this.platform.is('cordova')) {
          document.documentElement.classList.add("platform-android");
          that.store.remove(ConfigService.NOTICE_STATUS);
        }
      } else {
        this.statusBar.styleDefault();
        this.statusBar.overlaysWebView(true);//沉浸式并且悬浮透明
        this.statusBar.styleLightContent();
        if (this.platform.is('cordova')) {
          that.store.remove(ConfigService.NOTICE_STATUS);
          if (window.screen.height >= 812 && window.screen.width >= 375) {//iPhoneX以上
            document.documentElement.classList.add("iosXDevice");
          } else {
            document.documentElement.classList.add("iosDevice");
          }
        }
      }
      //更新app的弹出层操作
      if(this.platform.is('cordova')){
        this.onDownload();
      }
      //防止字体放大
      this.mobileAccessibility.usePreferredTextZoom(false);
      //屏蔽所有的console
      // console.log = function() {}     
    });
    this.store.get("token").then((data) => {
      $("app-root").attr("token", data);
    });
    this.store.get("sessid").then((data) => {
      $("app-root").attr("sessid", data);
    });
    this.store.get("uid").then((data) => {
      $("app-root").attr("uid", data);
    });
    //监听android设备硬件返回的事件
    this.platform.backButton.subscribe(() => {
      that.hideLotMenu();
      that.onClosePopwin();
    });
    this.network.onDisconnect().subscribe(() => {
      that.popWin.toast("亲，网络连接失败");
    });
    //获取url上邀请码inCode的值,并存储到本地
    this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((e: any) => {
      if (e.urlAfterRedirects == '/tabs/home' || e.urlAfterRedirects == '/tabs/index3rd') {
        let tempTarget = e.url.split('?');
        if (tempTarget.length >= 2) {
          let incode = ToolService.urlToObj(tempTarget[1])['incode'];
          if (!ToolService.isEmpty(incode)) {
            that.store.set(ConfigService.INCODE, incode);
          }
        }
      }
    });
    //判断是否兼容webp格式
    that.isWebp();
  }

  getSetData() {
    let that = this;
    this.http.get(UrlService.COMMON_SET, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        $("app-root").attr("encrypt", data.data.encrypt);
      } else if (data.code == ConfigService.FAIL_CODE) {

      } else if (data.code == ConfigService.LOGIN_CODE) {
        this.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  menuNet() {
    let that = this;
    this.http.get(UrlService.USER_LOTTERY, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let tt = ToolService.aesDecodeToJson(temp);
        if (!ToolService.isEmpty(tt)) {
          that.lots = tt;
          that.store.set(ConfigService.LOTTER_MENU, tt);
          console.log(tt);
        }
      }
    }, error => {
      console.log("error", error);
    });
  }

  openDid(menuId?: string) {
    this.menu.enable(true, menuId);
  }

  backHome() {
    this.navCtrl.navigateRoot("/");
    // this.eventS.publish("indexStartTime");
    this.hideLotMenu();
  }
  hideLotMenu() {
    $(".lotTwoMenu").css("display", "none");
    $(".lotMenu").css("display", "none");
  }
  /**
   * 选中菜单的一个跳转
   * @param key code
   * @param name  名称
   * @param type menu的id值
   * @param evnetName 事件的名称
   */
  toLotdetail(key, name, lotteryId, type, evnetName) {
    this.eventS.publish(evnetName, key, name, lotteryId);
    this.hideLotMenu();
  }

  hideMenu() {
    this.hideLotMenu();
  }

  initEvent() {
    let that = this;
    this.eventS.subscribe("getSlideMenu", function (isFroceUpdate) {
      if (isFroceUpdate) {//强制更新
        that.menuNet();
      } else {
        if (ToolService.isEmpty(that.lots)) {
          that.menuNet();
        }
      }
    }, true);
    this.eventS.subscribe("getMenuUserinfo", function () {
      that.openMenuOne();
    }, true)

    //第三的游戏处理相关操作
    this.eventS.subscribe("thirdWinShow", function (balance, show, thirdName, thirdBalance, thirdPlatformID, type) {
      that.allBalance = balance;
      that.isShowThirdWin = show;
      that.thirdName = thirdName;
      that.thirdBalance = thirdBalance;
      that.thirdPlatformID = thirdPlatformID;
      that.playType = type;
    }, true)




  }

  toggleGroup(item) {
    item.show = !item.show;
  }

  isGroupShown(item) {
    return !item.show;
  }
  /**
   * 侧滑菜单显示
   */
  openMenuOne() {

    this.store.get(ConfigService.USERINFO_KEY).then((data) => {
      let tempUserInfo = data;
      if (!ToolService.isEmpty(tempUserInfo)) {
        let userInfo = tempUserInfo;
        this.nickName = userInfo.uinfo.username;
        this.avatarImg = userInfo.uinfo.images;
        if (ToolService.isEmpty(this.avatarImg)) {
          this.isAvatar = false;
        } else {
          this.isAvatar = true;
        }
      }
    });
    this.store.get(ConfigService.MONEY_KEY).then((data) => {
      let tempMoney = data;
      if (!ToolService.isEmpty(tempMoney)) {
        let temp = tempMoney;
        this.money = ToolService.keepTwoDecimal(temp.credit2);
      }
    });



  }

  /**
   * 首页的弹出公共
   */
  async alertNotice() {
    let that = this;
    let status: any = 0;
    await this.store.get(ConfigService.NOTICE_STATUS).then((data) => {
      status = data;
    });
    if (status == 1 || status == "1") {
      return;
    }
    this.http.get(UrlService.ALERT_CONTENT, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let tt = ToolService.aesDecodeToJson(temp);
        console.log("弹出公告:", tt);
        if (!ToolService.isEmpty(tt)) {
          that.alertNoticeData = tt;
          if (that.alertNoticeData.length >= 1) {
            that.noticeData = that.alertNoticeData[0];
            that.selectNoticeMark = 0;
          }
          if (that.alertNoticeData.length > 1) {
            $(".next").addClass("has-next");
          }
          $("#notice_contain").show();
        }
      }
    }, error => {
      console.log("error", error);
    });
  }

  /**
   * 手动去关闭掉公告弹窗
   */
  onClosePopwin() {
    $("#notice_contain").hide();
    this.store.set(ConfigService.NOTICE_STATUS, 1);
  }

  /**
   * 切换上一页和下一页
   */
  onPageNotice(name: string) {
    let length = this.alertNoticeData.length;
    if (name == 'pre') {//上一页操作
      if (this.selectNoticeMark < 0) {
        $(".pre").removeClass("has-next");
        return;
      }
      if (this.selectNoticeMark > 0) {
        this.selectNoticeMark--;
        if (this.selectNoticeMark == 0) {
          $(".pre").removeClass("has-next");
        } else {
          $(".pre").addClass("has-next");
          $(".next").addClass("has-next");
        }
        this.noticeData = this.alertNoticeData[this.selectNoticeMark];
      }
    } else {//下一页操作
      if (this.selectNoticeMark < length) {
        this.selectNoticeMark++;
        if (this.selectNoticeMark == length) {
          this.selectNoticeMark--;
          return;
        }
        if (this.selectNoticeMark == length - 1) {
          $(".next").removeClass("has-next");
        }
        this.noticeData = this.alertNoticeData[this.selectNoticeMark];
        $(".pre").addClass("has-next");
      }
    }
  }

  //////////////////////////////第三方游戏的操作相关
  /**
   * 试玩
   */
  thirdTestPlay() {
    this.closeThirdWin();
    this.eventS.publish("thirdPlayFun", this.playType, this.thirdPlatformID, true, "");//测试账号玩家
  }
  /**
   * 正式的去玩
   */
  thirdPlay() {
    this.thirdInputVal = parseInt(this.thirdInputVal) + "";
    if (parseInt(this.thirdInputVal) > 10000) {
      this.popWin.toast("最大只能转化10000");
      return;
    }
    this.closeThirdWin();
    this.eventS.publish("thirdPlayFun", this.playType, this.thirdPlatformID, false, this.thirdInputVal);//正式号玩家
    this.thirdInputVal = "";
  }
  /**
   * 选择快捷金额
   * @param type 选择的金额类型
   */
  selectThirdMoney(type) {
    if (type != 'all') {
      this.thirdInputVal = type;
    } else {
      //将所有的余额处理
      this.thirdInputVal = parseInt(this.allBalance) + "";
    }
  }

  closeThirdWin() {
    this.isShowThirdWin = false;
  }
  /**
   * 是否兼容webp的图片
   */
  isWebp() {
    let image = new Image();
    image.src = "";
    image.onload = function () {
      if (image.width == 1) {
        document.documentElement.classList.add("webp");
      }
    }
  }


  //app内弹出更新的操作,从
  onDownload() {
    let that = this;
    //agentVal的值 0非代理非第三方,1代理非第三方,2非代理第三方，3代理第三方
    let agentVal = 0;
    if (ConfigService.isAgent == 1) {//代理
      if (ConfigService.is3rd) {//第三方
        agentVal = 3;
      } else {//非第三方
        agentVal = 1;
      }
    } else {//非代理
      if (ConfigService.is3rd) {
        agentVal = 2;
      } else {
        agentVal = 0;
      }
    }
    that.versionNo=ConfigService.APP_VERSION;
    let obj = "{\"agent\":\"" + agentVal + "\",\"version_number\":\"" + ConfigService.APP_VERSION + "\"}";
    this.http.get(UrlService.USER_SYSTEMUPDATE, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        console.log("更新的数据:",res);
        if (ToolService.versionfunegt(res.version_number, ConfigService.APP_VERSION) && (res.is_forced == 1 || res.is_forced == "1")) {
          //强制更新
          that.isForce = true;
          that.isUpdate = true;
          that.updateContent = res.update_content;
          that.iosDownUrl = res.plist_url;
          that.androidDownUrl = res.app_url;
        } else if (ToolService.versionfunegt(res.version_number, ConfigService.APP_VERSION) && (res.is_forced == 0 || res.is_forced == "0")) {
          //可以更新
          that.isForce = false;
          that.isUpdate = true;
          that.updateContent = res.update_content;
          that.iosDownUrl = res.plist_url;
          that.androidDownUrl = res.app_url;
        } else if (!ToolService.versionfunegt(res.version_number, ConfigService.APP_VERSION)) {
          //已经是最新版本不要任何操作
          that.isUpdate=false;
        }
      }
    }, error => {
      console.log("error", error);
    });
  }

  /**
   * app更新的关闭
   */
  onUpdateClose() {
    this.isUpdate = false;
  }

  /**
   * app的更新操作
   */
  onUpdateApp() {
    this.downByUrl(this.iosDownUrl,this.androidDownUrl);
  }


  downByUrl(iosUrl,androidUrl){
    if(this.platform.is("cordova") && this.platform.is("android")){
      this.downApk(androidUrl);
    }else if(this.platform.is("cordova") && this.platform.is("ios")){
      //window.location.href=iosUrl;
      //const browser = this.iab.create("https://yll1024335892.github.io/yll_ipa/", '_system');
      console.log("ios的下载连接:",iosUrl);
      this.iab.create(iosUrl, '_system');
    }
  }

  async downApk(url){
    //"http://web.tw8999.com/android.apk"
    let that=this;
    this.onUpdateClose();//将界面关闭
    const fileTransfer:FileTransferObject=this.transfer.create();
    let loadObj = await this.loading.create({
      message: '下载:0%',
      duration: 0
    });
    await loadObj.present();
    fileTransfer.download(url,this.file.externalDataDirectory+"wlh.apk").then((entry)=>{ 
        that.fileOpener.open(entry.toURL(),'application/vnd.android.package-archive').then((res)=>{
      },(e)=>{
         
      }).catch(e=>{
          
      });
    },(error)=>{
       
    });
    fileTransfer.onProgress((event:ProgressEvent)=>{
        let num=Math.ceil(event.loaded/event.total *100);
        if(num==100){
          loadObj.message="下载完成";
          console.log("完成");
        }else{
          loadObj.message="下载:"+num+"%";
          console.log("下载:"+num);
        }
    });



  }



}
